package com.bdsy.common.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Map;
import java.util.UUID;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.core.io.ClassPathResource;


/**
 * 
 * ClassName: FastDFSUtils
 * Function: 操作fastDFS工具类
 * Reason: TODO ADD REASON(可选).
 * date: 2017年6月1日 上午10:50:46
 *
 * @author LCH
 * @version 
 * @since JDK 1.7
 */
public class FastDFSUtils {
	
	//提供空参构造
	private FastDFSUtils() {
	}

	
	private static TrackerServer getTrackerServer() throws Exception {
		
		ClassPathResource resource = new ClassPathResource("fdfs_client.conf");
		ClientGlobal.init(resource.getClassLoader().getResource("fdfs_client.conf").getPath());
		return new TrackerClient().getConnection();
	}

	/**
	 * @功能: 获取元数据信息，将metamap转换成元数据信息，元数据本身也是key-value的形式，记录文件的相关信息
	 * @作者: LCH
	 * @param metaMap元数据map集合
	 * @return 返回元数据数组
	 */
	private static NameValuePair[] convertNameValuePair(Map<String, String> metaMap) {
		if (metaMap!=null && metaMap.size()>0) {
			int i = 0;
			NameValuePair[] metaArray = new NameValuePair[metaMap.size()];
			for (Map.Entry<String, String> entry : metaMap.entrySet()) {
				metaArray[i++] = new NameValuePair(entry.getKey(), entry.getValue());
			}
			return metaArray;
		}
		return null;
	}

	/**
	 * @功能: 获取文件http地址，可以在浏览器中直接访问，页面显示的的地址
	 * @作者: LCH
	 * @param groupName组名，例："group1"
	 * @param remoteFileName目标文件名，例："M00/00/00/wKgBbVkvF36ASWSiAAEV7IgL0pU480.jpg"
	 * @return 访问路径，例： http://192.168.1.109:80/group1/M00/00/00/wKgBbVkvF36ASWSiAAEV7IgL0pU480.jpg

	 * @throws Exception 
	 */
	public static String getFileUrl(String groupName, String remoteFileName)  {
		TrackerServer trackerServer = null;
		try {
			trackerServer = getTrackerServer();
			InetAddress address = trackerServer.getInetSocketAddress().getAddress();
			if (address != null) {
				return "http://" + address.getHostAddress() + ":" + ClientGlobal.g_tracker_http_port + "/" + groupName + "/" + remoteFileName;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (trackerServer != null) trackerServer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * @功能: 删除文件
	 * @作者: LCH
	 * @param groupName组名：例："group1"
	 * @param remoteFileName例："M00/00/00/wKgBbVkvF36ASWSiAAEV7IgL0pU480.jpg"
	 * @return true删除成功，false删除失败
	 */
	public static boolean deleteFile(String groupName, String remoteFileName) {
		TrackerServer trackerServer = null;
		try {
			trackerServer = getTrackerServer();
			StorageClient storageClient = new StorageClient(trackerServer, null);
			if (storageClient.delete_file(groupName, remoteFileName) == 0) return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (trackerServer != null) trackerServer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	/**
	 * @功能: 上传文件到storage server
	 * @作者: LCH
	 * @param b 文件字节数组 可以在FileUtils找到转换方法
	 * @param fileExtName 文件扩展名(不包含".")
	 * @param metaMap 文件元信息是指文件的相关属性，以键值对（key value pair）方式表示，如：width=1024，其中的key为width，value为1024。
	 * 			文件meta data是文件属性列表，可以包含多个键值对。其中value的值建议范围：4KB < file_size <500MB。
	 * @return 成功,results[0]:the group name to store the file,results[1]:the new created filename;<br/>
	 *         失败,返回null
	 */
	public static String[] uploadFile(byte[] b, String fileExtName, Map<String, String> metaMap) {
		TrackerServer trackerServer = null;
		try {
			trackerServer = getTrackerServer();
			StorageClient storageClient = new StorageClient(trackerServer, null);
			return storageClient.upload_file(b, fileExtName, convertNameValuePair(metaMap));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (trackerServer != null) trackerServer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * @功能: 上传文件到storage server
	 * @作者: LCH
	 * @param filePath 文件路径 例："C:\\Users\\Administrator\\Desktop\\2008030811454996ecd.jpg"
	 * @param fileExtName 文件扩展名(不包含".") 例："jpg"
	 * @param metaMap 文件元信息 例：
	 * 	    Map<String,String> metaMap=new HashMap<String,String>();
	 * 		metaMap.put("pic_id","10000");
	 * 		metaMap.put("hight", "200");
	 * 		metaMap.put("size", "378");
	 * @return 成功,results[0]:the group name to store the file 例：group1
	 * 				results[1]:the new created filename 例：M00/00/00/wKgBbVkvMk2AN-J4AAEV7IgL0pU968.jpg
	 *         失败,返回null
	 */
	public static String[] uploadFile(String filePath, String fileExtName, Map<String, String> metaMap) {
		TrackerServer trackerServer = null;
		try {
			trackerServer = getTrackerServer();
			StorageClient storageClient = new StorageClient(trackerServer, null);
			return storageClient.upload_file(filePath, fileExtName, convertNameValuePair(metaMap));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (trackerServer != null) trackerServer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * @功能: 下载文件
	 * @作者: LCH
	 * @param groupName 例：group1
	 * @param remoteFileName 例：M00/00/00/wKgBbVkvMk2AN-J4AAEV7IgL0pU968.jpg
	 * @return 返回字节数组
	 */
	public static byte[] downloadFile(String groupName, String remoteFileName) {
		TrackerServer trackerServer = null;
		try {
			trackerServer = getTrackerServer();
			StorageClient storageClient = new StorageClient(trackerServer, null);
			return storageClient.download_file(groupName, remoteFileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (trackerServer != null) trackerServer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * @功能: 下载文件
	 * @作者: LCH
	 * @param groupName 例：group1
	 * @param remoteFileName 例：M00/00/00/wKgBbVkvMk2AN-J4AAEV7IgL0pU968.jpg
	 * @param filePath 下载路径可以自动创建，下载的文件名由UUID随机生成。 例：F:\\develop\\upload\\
	 * @param extFileName 生成文件名的后缀，不包含（.） 例 ：jpg
	 * @return true下载成功  false下载失败
	 */
	public static boolean downloadFile(String groupName, String remoteFileName, String filePath,String extFileName) {
		TrackerServer trackerServer = null;
		
		try {
			File file=new File(filePath);
			if(!file.exists()){
			file.mkdirs();
			
			}
			trackerServer = getTrackerServer();
			StorageClient storageClient = new StorageClient(trackerServer, null);
		    String fileName=filePath+UUID.randomUUID().toString().replace("-", "")+"."+extFileName;

			if (storageClient.download_file(groupName, remoteFileName, fileName) == 0) 
				return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (trackerServer != null) 
					trackerServer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	

}


